import cgi
import os

from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from droidguide_classes import *

def checkForServerEvents(self, droidGuideUser_key):
    #get list of services for the user
    eventData = ''
    q = UserToService.gql("WHERE droidGuideUser_key = :dgkey",
               dgkey=droidGuideUser_key)
    for userToService in q:
        service = getObject(userToService.service_key)
        # getting all events related to user
        q2 = DroidGuideEvent.gql("WHERE droidGuideUser_key = :dgkey",
                dgkey=droidGuideUser_key)
        L = []
        for event in q2:
            # if the event type equals the service type and the service is available
            if event.type == service.type and service.state == 'AVAILABLE' and event.state == 'AVAILABLE':
                event.state = 'CONSUMED'
                event.put()
                if event.data:
                    eventData = event.data
                else:
                    eventData = service.data
                try:
                    # if the service has not been put on the list yet, it will throw an error
                    # if it exists, there will be no error
                    i = L.index(service)
                except ValueError:
                    L.append(service)
        # for each service the user is subscribed to
        for service in L:
            service_key = str(service.key())
            # getting the user subscriptions of each service
            q3 = UserToService.gql("WHERE droidGuideUser_key = :dgkey AND service_key = :skey",
               dgkey=droidGuideUser_key, skey=service_key)
            userToService = q3.get()
            if userToService:
                serviceEvent = ServiceEvent()
                serviceEvent.userToService_key = str(userToService.key())
                serviceEvent.type = 'ONE-TIME'
                serviceEvent.state = 'CONSUMED'
                serviceEvent.data = eventData
                serviceEvent.put()
                self.response.out.write(serviceEvent.to_xml())

def consumeServerEvent(self):
    serviceEvent_key = self.request.get('serv_evt_key')
    serviceEvent = getObject(serviceEvent_key)
    if serviceEvent:
        serviceEvent.state = 'COMSUMED'
        serviceEvent.put()
        addMessage('event consumed successfully', self)

def handleEvent(self):
      type = self.request.get('type')
      data = self.request.get('data')
      source = self.request.get('source')
      droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
      #print '%s' % droidGuideUser_key
      if droidGuideUser_key:
          droidGuideUser = getObject(droidGuideUser_key)          
          if droidGuideUser:
              dgEvent = DroidGuideEvent()
              dgEvent.type = type
              dgEvent.droidGuideUser_key = str(droidGuideUser.key())
              dgEvent.source = source
              dgEvent.data = data
              if source == 'service' or source == 'server':
                  dgEvent.state = 'AVAILABLE'
              dgEvent.put()
              printObjectShort(self, droidGuideUser)
              self.response.out.write(dgEvent.to_xml())
          else:
              addMessage('droid guide user not found', self)
          
      else:
          addMessage('event cannot be persisted because there is no droid guide user associated with it', self)

def listEventsFromUser(self):
    droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
    if droidGuideUser_key:
        q = DroidGuideEvent.gql("WHERE droidGuideUser_key = :dgkey",
                    dgkey=droidGuideUser_key)
        for event in q:
            self.response.out.write(event.to_xml())
    else:
        listObjects(DroidGuideEvent, self)
        
class Process(webapp.RequestHandler):
  def get(self):
      operation = self.request.get('operation')
      startDroidGuideMessage(self)
      
      # adding events to server
      #http://localhost:8080/eventservice/process?operation=save&droidGuideUser_key=agpkcm9pZGd1aWRlchULEg5Ecm9pZEd1aWRlVXNlchiiAQw&type=profile&source=user&data=change%20of%20mood
      if operation == 'save':
          handleEvent(self)
      # list all events
      #http://localhost:8080/eventservice/process?operation=list
      elif operation == 'list':
          listEventsFromUser(self)
      # delete all events
      #http://localhost:8080/eventservice/process?operation=deleteall
      elif operation == 'deleteAll':
          deleteAll(DroidGuideEvent)
      # confirm consumption of serve event
      # http://localhost:8080/eventservice/process?operation=consume&serv_evt_key=agpkcm9pZGd1aWRlchMLEgxTZXJ2aWNlRXZlbnQYuwEM
      elif operation == 'consume':
          consumeServerEvent(self)
      # list all service events in the system
      # http://localhost:8080/eventservice/process?operation=listServerEvents
      elif operation == 'listAll':
          listObjects(ServiceEvent, self)    
    
      # get all server events related to user
      elif operation == 'getServerEvents':
          droidGuideUser_key = self.request.get(DROID_GUIDE_USER_KEY)
          checkForServerEvents(self, droidGuideUser_key)
          
      finishDroidGuideMessage(self)

application = webapp.WSGIApplication([('/eventservice/process', Process)], debug=True)


def main():
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
